package cn.edu.buaa.treehole.controller;

import cn.edu.buaa.treehole.service.NameService;
import cn.edu.buaa.treehole.service.SignatureService;
import cn.edu.buaa.treehole.service.exception.NameNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.configurationprocessor.json.JSONException;
import org.springframework.boot.configurationprocessor.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/admin")
public class AdministorController {
    private static final String ADMIN_SIGNATURE = "admin";

    private final SignatureService signatureService;
    private final NameService nameService;

    @Autowired
    public AdministorController(SignatureService signatureService, NameService nameService) {
        this.signatureService = signatureService;
        this.nameService = nameService;
    }

    @RequestMapping("/get_signature")
    @ResponseBody
    String getSignature(
            @RequestParam("pid") long pid,
            @RequestParam("name") String name,
            @RequestParam("adsig") String adsig) throws JSONException {
        JSONObject ret = new JSONObject();

        if (!adsig.equals(ADMIN_SIGNATURE)) {
            ret.put("status", "signature_wrong");
            return ret.toString();
        }

        try {
            long nid = nameService.getNid(name);
            String signature = signatureService.getSignatureById(pid, nid);
            ret.put("signature", signature);
            ret.put("status", "success");
        } catch (NameNotFoundException e) {
            ret.put("status", "name_not_found");
        } catch (Exception e) {
            ret.put("status", "exception");
        }
        return ret.toString();
    }

    @RequestMapping("mark")
    String markAdmin(
            @RequestParam("pid") long pid,
            @RequestParam("name") String signature,
            @RequestParam("adsig") String adsig) throws JSONException {
        JSONObject ret = new JSONObject();
        ret.put("status", "not_implement");
        // TODO
        return ret.toString();
    }
}
